package com.laber.controller;

import com.laber.domain.Result;
import com.laber.utils.MinioUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping
public class FileUploadController {

    @Autowired
    private MinioUtils minioUtils;

    @Value("${minio.bucketName}")
    private String bucketName;


//    @PostMapping("/upload")
//    public Result<String> upload(MultipartFile file) throws IOException {
//        //把文件的内容存在服务器本地上
//        String originalFilename = file.getOriginalFilename();
//        //保证文件的名字是唯一的，从而防止文件被覆盖
//        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
//        file.transferTo(new File("/home/laber/workspace/IdeaProject/Springboot3_Vue3/big-event/src/main/resources/static/"
//                + fileName));
//        return Result.success("url访问地址: ...");
//    }

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws IOException {
        //保证文件的名字是唯一的，从而防止文件被覆盖，minioUtils工具中使用了时间戳重命名文件来保证唯一性
        String bucketAndFileName = minioUtils.upload(file, bucketName);
        String fileName = bucketAndFileName.substring(bucketAndFileName.lastIndexOf("/") + 1);
        String fileUrl = minioUtils.getFileUrl(bucketName, fileName);

        //由于设置minio big-event桶访问为public，因此只需提供？之前的rul即可
        String resUrl = fileUrl.substring(0, fileUrl.indexOf("?"));

        return Result.success(resUrl);
    }
}
